package dxlateplate;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class ClearDatastoreServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(ClearDatastoreServlet.class.getName());

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

        PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + LatePlate.class.getName() + " order by value asc";
        List<LatePlate> latePlateList = (List<LatePlate>) pm.newQuery(query).execute();
        Date date = new Date();
        int currentDay = date.getDay();
        int hours = date.getHours() - 5;

        for(LatePlate plate: latePlateList) {
        	if(!plate.isPermanent()) {
	            if(plate.getValue() < currentDay) {
	                pm.deletePersistent(plate);
	            } else if(((plate.getType() == 1) && (plate.getValue() <= currentDay)) && (hours > 13)) {
	                //Delete lunch late plates before dinner
	                pm.deletePersistent(plate);
	            }
        	}
        }

        pm.close();

        resp.sendRedirect("/latePlateHome.jsp");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
        doGet(req, resp);
    }
}
